#!/usr/bin/bash

set -e

{ lsmod | grep i2c_dev ; } || modprobe -v i2c-dev
{ lsmod | grep led_ugreen ; } || modprobe -v led-ugreen

i2c_dev=$(i2cdetect -l | grep "SMBus I801 adapter" | grep -Po "i2c-\d+")

if [ $? = 0 ]; then 
        echo "Found I2C device /dev/${i2c_dev}"
        dev_path=/sys/bus/i2c/devices/$i2c_dev/${i2c_dev/i2c-/}-003a
        if [ ! -d $dev_path ]; then
            echo "led-ugreen 0x3a" > /sys/bus/i2c/devices/${i2c_dev}/new_device
        elif [ "$(cat $dev_path/name)" != "led-ugreen" ]; then
            echo "ERROR: the device ${i2c_dev/i2c-/}-003a has been registered as $(cat $dev_path/name)"
            exit 1
        fi
else
        echo "I2C device not found!"
fi
